package com.smsc.headend.task.engine.executor.impl.ansi;

import cn.hutool.core.collection.CollUtil;
import com.smsc.headend.module.asset.entity.Meter;
import com.smsc.headend.module.data.dto.AnsiSubDataItemDTO;
import com.smsc.headend.module.data.dto.DataItemDTO;
import com.smsc.headend.module.fwu.entity.TemplateFwUpgrade;
import com.smsc.headend.module.protocol.cosem.util.ByteUtils;
import com.smsc.headend.module.task.dto.AtomicTask;
import com.smsc.headend.module.task.dto.AtomicTaskState;
import com.smsc.headend.module.task.dto.Task;
import com.smsc.headend.task.engine.exception.UDISTaskExecutorException;
import com.smsc.headend.task.engine.executor.TaskExecutor;
import com.smsc.headend.task.engine.handler.impl.ActionSuccessHandler;
import com.smsc.headend.task.engine.handler.impl.firmware.FirmwareSuccessHandler;
import com.smsc.headend.task.engine.service.ConnectorService;
import com.smsc.headend.task.engine.service.asset.AssetService;
import com.smsc.headend.task.engine.service.firmware.FirmwareService;
import com.smsc.headend.task.engine.service.task.TaskPacketService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

@Slf4j
public class UpdateControlExecutor implements TaskExecutor {
    @Autowired
    TaskPacketService packetService;
    @Autowired
    ConnectorService connectorService;
    @Autowired
    AssetService assetService;
    @Autowired
    FirmwareService firmwareService;

    @Override
    public AtomicTaskState execute(Task task, AtomicTask atomicTask) throws UDISTaskExecutorException {
        Meter meter = getMeter(task, assetService);
        AnsiSubDataItemDTO dataItemDTO = new AnsiSubDataItemDTO();
        dataItemDTO.setTableId(0x0858);
        dataItemDTO.setTableOffset(0);
        dataItemDTO.setByteCount(2);
        dataItemDTO.setRoleId(2);
        List<DataItemDTO> dataItemList = CollUtil.newArrayList(dataItemDTO);
        AtomicTaskState atomicState = createAtomicState(FirmwareSuccessHandler.class);
        byte[] packets = packetService.writeSimpleDataPacket(dataItemList, meter, new byte[]{0x00, 0x01}, null);
        log.debug(ByteUtils.byteToHexString(packets));
        connectorService.sendPacket(task, atomicTask, 2, task.getIsODR(), packets);

        return atomicState;
    }

    @Override
    public Boolean handleFailure(Task task, AtomicTask atomicTask, String message) {
        if (UDISTaskExecutorException.COM_STATUS_EXCEPTION.equalsIgnoreCase(message)) {
            log.warn("fwu update control pause because of com offline");
            return false;
        }
        firmwareService.saveFwuReport(task, atomicTask, -1, TemplateFwUpgrade.TaskType.ImageTransfer, "fwu update control execute failed", null);
        return true;
    }
}
